﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cow.Module;

namespace Cow.Handler
{
    public class ExportSchemaHandler : ExportFromStringBuilder
    {
        public override string SuffixName
        {
            get { return ".sql"; }
        }

        protected override string TemplatePath
        {
            get { return String.Empty; }
        }

        protected override List<String> GetExportContent(Design design)
        {
            StringBuilder sb = new StringBuilder("Create Table");
            sb.Append(String.Format("[{0}](\n", design.ModuleName));
            foreach (var item in design.DefinitionInfo)
            {
                var sqlType = design.DataTypeInfo.FirstOrDefault(i => i.Name.Equals(item.DataType)).SqlType;
                if (!String.IsNullOrWhiteSpace(item.Length)) 
                {
                    sqlType += "(" + item.Length + ")";
                }
                sb.Append(String.Format("[{0}] {1} {2} ", item.Property, sqlType, item.IsNull ? "NULL" : "NOT NULL"));
                //添加主键
                if (item.IsKey)
                {
                    sb.Append(String.Format("CONSTRAINT [PK_{0}_{1}] PRIMARY KEY ", design.ModuleName, item.Property));
                }
                //默认值
                if (!String.IsNullOrWhiteSpace(item.DefaultValue))
                {
                    sb.Append(String.Format("DEFAULT {0} ", item.DefaultValue));
                }
                sb.Append(",\n");
            }
            String content = sb.ToString().TrimEnd(',') + ")\n";
            List<String> valueList = new List<string>();
            valueList.Add(content);
            return valueList;
        }
    }
}
